package net.wds.ssbus.modules.ssbus.service.impl;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.wds.ssbus.modules.dict.entity.TbBaseDictitemEntity;
import net.wds.ssbus.modules.ssbus.mapper.TbSsbusTaskMapper;
import net.wds.ssbus.modules.ssbus.pojo.TbSsbusChannelEntrty;
import net.wds.ssbus.modules.ssbus.pojo.TbSsbusTaskEntrty;
import net.wds.ssbus.modules.ssbus.service.TbSsbusTaskService;
import net.wds.ssbus.modules.ssbus.util.GetIpAndPortUtils;
import net.wds.ssbus.modules.sys.controller.AbstractController;
import net.wds.ssbus.modules.sys.entity.SysUserEntity;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Component
@Service("tbSsbusTaskService")
public class TbSsbusTaskServiceImp extends AbstractController implements TbSsbusTaskService {
    @Autowired
    private Scheduler scheduler;
    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TbSsbusTaskServiceImp.class);

    @Resource
    private TbSsbusTaskMapper tbSsbusTaskMapper;

    @Override
    public IPage<TbSsbusTaskEntrty> list(int pageNo, int pageSize, String key) {
        Page<TbSsbusChannelEntrty> page = new Page(pageNo,pageSize);
        IPage<TbSsbusTaskEntrty> list = tbSsbusTaskMapper.list(page,key);
        return list;
    }

    @Override
    public void upCommonlog(String id, Integer commonlog) {
        tbSsbusTaskMapper.upCommonlog(id,commonlog);
    }

    @Override
    public void upFaillog(String id, Integer faillog) {
        tbSsbusTaskMapper.upFaillog(id,faillog);
    }

    @Override
    public void deletes(String[] id) {
        tbSsbusTaskMapper.deletes(id);
    }

    @Override
    public TbSsbusTaskEntrty getById(String id) {
        return tbSsbusTaskMapper.getById(id);
    }

    @Override
    public void addQuartz(TbSsbusTaskEntrty tbSsbusTaskEntrty) {
        SysUserEntity u=getUser();
        tbSsbusTaskEntrty.setId(UUID.randomUUID().toString().toLowerCase());
        tbSsbusTaskEntrty.setAddUser(u.getUsername());
        tbSsbusTaskEntrty.setAddTime(new Date());
        tbSsbusTaskEntrty.setStatus(24);
        tbSsbusTaskEntrty.setExechost(GetIpAndPortUtils.getLocalIP());
        tbSsbusTaskEntrty.setExecport(GetIpAndPortUtils.getLocalPort());
        tbSsbusTaskMapper.save(tbSsbusTaskEntrty);
    }

    @Override
    public boolean update(TbSsbusTaskEntrty tbSsbusTaskEntrty) {
        SysUserEntity u=getUser();
        Boolean b =CronExpression.isValidExpression(tbSsbusTaskEntrty.getTasktime());
        if(b=true){
            tbSsbusTaskEntrty.setEditUser(u.getUsername());
            tbSsbusTaskEntrty.setEditTime(new Date());
            return tbSsbusTaskMapper.update(tbSsbusTaskEntrty);
        }else {
            return b;
        }

    }

    @Override
    public  List<TbBaseDictitemEntity> status() {
        return tbSsbusTaskMapper.status();
    }

    @Override
    public void delete(String id) {
        try {
            scheduler.pauseTrigger(TriggerKey.triggerKey(id));//暂停触发器
            scheduler.unscheduleJob(TriggerKey.triggerKey(id));//移除触发器
            scheduler.deleteJob(JobKey.jobKey(id));//删除Job
            tbSsbusTaskMapper.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public String startTask(String taskId) {
        PostMethod method = null;
        String startUrl = "";
        String result = "";
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        //SsbusTask sst = coreServiceExtension.getEntityById(SsbusTask.class, taskId);
        TbSsbusTaskEntrty tbSsbusTaskEntrty= tbSsbusTaskMapper.getById(taskId);
        session.setAttribute("name", tbSsbusTaskEntrty.getName());
        session.setAttribute("id", taskId);
        if(null != tbSsbusTaskEntrty.getExechost() && !"".equals(tbSsbusTaskEntrty.getExechost().trim())){
            if(null != tbSsbusTaskEntrty.getExecport() && !"".equals(tbSsbusTaskEntrty.getExecport()))
                startUrl = "http://"+tbSsbusTaskEntrty.getExechost()+":"+tbSsbusTaskEntrty.getExecport()+"/wds-ssbus-core/ssbusCore/task/start";
            else
                startUrl = "http://"+tbSsbusTaskEntrty.getExechost()+"/wds-ssbus-core/ssbusCore/task/start";
        }else{
            result = "{\"success\":false,\"data\":\"未指定任务执行服务器IP。\"}";
            return result;
        }
        /*请求任务启动接口*/
        try {
            HttpClient client = new HttpClient();
            method = new PostMethod(startUrl);
            method.setParameter("taskId", taskId);
            HttpMethodParams parames = method.getParams();
            parames.setContentCharset("utf-8");
            int code = client.executeMethod(method);
            String response = method.getResponseBodyAsString();
            if (code != HttpStatus.SC_OK) {
                result = "{\"success\":false,\"data\":\"接口请求失败,错误代码："+code+"\"}";
                LOGGER.error("接口请求失败:任务编号："+taskId+"，请求服务器地址："+ tbSsbusTaskEntrty.getExechost() +"，错误代码："+code+"");
                session.setAttribute("e", ""+code+"");
            } else {
                if (response.equals("OK")) {
                    result = "{\"success\":true,\"data\":\"执行任务成功\"}";
                    int status = 23;
                    tbSsbusTaskMapper.upadtestatus(taskId, status);
                }else{
                    result = "{\"success\":false,\"data\":\"执行任务失败,错误信息："+response+"\"}";
                    LOGGER.error("执行任务失败:任务编号："+taskId+"，执行服务器："+ tbSsbusTaskEntrty.getExechost() +"， 错误信息："+response+"");
                }
            }
            method.releaseConnection();
        } catch (HttpException e) {
            e.printStackTrace();
            session.setAttribute("e", e.toString());
            result = "{\"success\":false,\"data\":\"请求服务器失败,错误信息："+e.getMessage()+"\"}";
            LOGGER.error("请求服务器失败:任务编号："+taskId+"，执行服务器："+ tbSsbusTaskEntrty.getExechost() +"， 错误信息："+e.getMessage()+"");
        } catch (IOException e) {
            e.printStackTrace();
            session.setAttribute("e", e.toString());
            result = "{\"success\":false,\"data\":\"请求服务器失败,错误信息："+e.getMessage()+"\"}";
            LOGGER.error("请求服务器失败:任务编号："+taskId+"，执行服务器："+ tbSsbusTaskEntrty.getExechost() +"， 错误信息："+e.getMessage()+"");
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        session.setAttribute("result", result);
        return result;
    }

    @Override
    public String stopTask(String taskId) {
        PostMethod method = null;
        String startUrl = "";
        String result = "";
        /*设置访问接口URL*/
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpSession session = request.getSession();
        //SsbusTask sst = coreServiceExtension.getEntityById(SsbusTask.class, taskId);
        TbSsbusTaskEntrty tbSsbusTaskEntrty= tbSsbusTaskMapper.getById(taskId);
        session.setAttribute("name", tbSsbusTaskEntrty.getName());
        session.setAttribute("date", DateUtil.formatDateTime(new Date()));
        session.setAttribute("id", taskId);
        if(null != tbSsbusTaskEntrty.getExechost() && !"".equals(tbSsbusTaskEntrty.getExechost().trim())){
            if(null != tbSsbusTaskEntrty.getExecport() && !"".equals(tbSsbusTaskEntrty.getExecport()))
                startUrl = "http://"+tbSsbusTaskEntrty.getExechost()+":"+tbSsbusTaskEntrty.getExecport()+"/wds-ssbus-core/ssbusCore/task/stop";
            else
                startUrl = "http://"+tbSsbusTaskEntrty.getExechost()+"/wds-ssbus-core/ssbusCore/task/stop";
        }else{
            result = "{\"success\":false,\"data\":\"未指定任务执行服务器IP。\"}";
            return result;
        }
        /*请求任务启动接口*/
        try {
            HttpClient client = new HttpClient();
            method = new PostMethod(startUrl);
            method.setParameter("taskId", taskId);
            HttpMethodParams parames = method.getParams();
            parames.setContentCharset("utf-8");
            int code = client.executeMethod(method);
            String response = method.getResponseBodyAsString();
            if (code != HttpStatus.SC_OK) {
                result = "{\"success\":false,\"data\":\"接口请求失败,错误代码："+code+"\"}";
                session.setAttribute("e", ""+code+"");
                LOGGER.error("接口请求失败:任务编号："+taskId+"，请求服务器地址："+ tbSsbusTaskEntrty.getExechost() +"，错误代码："+code+"");
            } else {
                if (response.equals("OK")) {
                    result = "{\"success\":true,\"data\":\"停止任务成功\"}";
                    int status =24;
                    tbSsbusTaskMapper.upadtestatus(taskId, status);
                }else{
                    result = "{\"success\":false,\"data\":\"停止任务失败,错误信息："+response+"\"}";
                    LOGGER.error("停止任务失败:任务编号："+taskId+"，执行服务器："+ tbSsbusTaskEntrty.getExechost() +"， 错误信息："+response+"");
                }
            }
            method.releaseConnection();
        } catch (HttpException e) {
            e.printStackTrace();
            session.setAttribute("e", e.toString());
            result = "{\"success\":false,\"data\":\"请求服务器失败,错误信息："+e.getMessage()+"\"}";
            LOGGER.error("请求服务器失败:任务编号："+taskId+"，执行服务器："+ tbSsbusTaskEntrty.getExechost() +"， 错误信息："+e.getMessage()+"");
        } catch (IOException e) {
            e.printStackTrace();
            session.setAttribute("e", e.toString());
            result = "{\"success\":false,\"data\":\"请求服务器失败,错误信息："+e.getMessage()+"\"}";
            LOGGER.error("请求服务器失败:任务编号："+taskId+"，执行服务器："+ tbSsbusTaskEntrty.getExechost() +"， 错误信息："+e.getMessage()+"");
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
        return result;
    }

}
